// SmartInput 浏览器扩展后台脚本 - 简化版本

let isConnected = false;
let deviceId = null;
let currentServer = null;
let connectionCheckInterval = null;

// 获取可能的服务器地址
function getServerUrls() {
  return [
    'wss://mensanyun.com'
  ];
}

// 生成设备ID
function generateDeviceId() {
  const timestamp = Date.now();
  const random = Math.random().toString(36).substring(2, 15);
  return `browser_chrome_${timestamp}_${random}`;
}

// 测试服务器连接
async function testServerConnection(url) {
  try {
    console.log(`测试连接: ${url}`);
    const response = await fetch(`${url}/health`, {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json'
      }
    });
    
    if (response.ok) {
      const data = await response.json();
      console.log(`✅ 服务器连接成功: ${url}`, data);
      return true;
    } else {
      console.log(`❌ 服务器响应错误: ${url} - ${response.status}`);
      return false;
    }
  } catch (error) {
    console.log(`❌ 服务器连接失败: ${url} - ${error.message}`);
    return false;
  }
}

// 连接到服务器
async function connectToServer() {
  const urls = getServerUrls();
  
  for (const url of urls) {
    const connected = await testServerConnection(url);
    if (connected) {
      currentServer = url;
      isConnected = true;
      
      console.log(`🎉 连接成功: ${url}`);
      
      // 通知popup连接状态
      notifyConnectionStatus(true, url);
      
      // 开始定期检查连接状态
      startConnectionCheck();
      return;
    }
  }
  
  // 所有服务器都连接失败
  console.log('❌ 所有服务器连接失败');
  isConnected = false;
  currentServer = null;
  notifyConnectionStatus(false, null);
  
  // 5秒后重试
  setTimeout(connectToServer, 5000);
}

// 通知popup连接状态
function notifyConnectionStatus(connected, serverUrl) {
  chrome.runtime.sendMessage({
    type: 'CONNECTION_STATUS',
    connected: connected,
    serverUrl: serverUrl
  }).catch(() => {
    // popup可能未打开，忽略错误
  });
}

// 开始连接检查
function startConnectionCheck() {
  if (connectionCheckInterval) {
    clearInterval(connectionCheckInterval);
  }
  
  connectionCheckInterval = setInterval(async () => {
    if (currentServer) {
      const connected = await testServerConnection(currentServer);
      if (!connected) {
        console.log('连接丢失，尝试重新连接...');
        isConnected = false;
        currentServer = null;
        connectToServer();
      }
    }
  }, 10000); // 每10秒检查一次
}

// 扩展安装时初始化
chrome.runtime.onInstalled.addListener(async () => {
  console.log('SmartInput 扩展已安装');
  
  // 生成设备ID
  const result = await chrome.storage.local.get(['deviceId']);
  if (!result.deviceId) {
    deviceId = generateDeviceId();
    await chrome.storage.local.set({ deviceId });
  } else {
    deviceId = result.deviceId;
  }
  
  console.log('设备ID:', deviceId);
  
  // 连接到服务器
  connectToServer();
});

// 扩展启动时连接服务器
chrome.runtime.onStartup.addListener(() => {
  console.log('SmartInput 扩展启动');
  connectToServer();
});

// 处理popup消息
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  console.log('收到消息:', message);
  
  switch (message.type) {
    case 'GET_STATUS':
      sendResponse({
        connected: isConnected,
        deviceId: deviceId,
        currentServer: currentServer,
        pairedDevices: []
      });
      break;
      
    case 'RECONNECT':
      console.log('手动重新连接');
      connectToServer();
      sendResponse({ success: true });
      break;
      
    case 'START_PAIRING':
      // TODO: 实现配对功能
      console.log('开始配对');
      sendResponse({ success: true });
      break;
      
    default:
      sendResponse({ error: 'Unknown message type' });
  }
  
  return true; // 保持消息通道开放
});

// 处理标签页更新
chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
  if (changeInfo.status === 'complete' && tab.url) {
    // 可以在这里注入内容脚本或执行其他操作
  }
});

console.log('SmartInput 后台脚本已加载');
